package yhao.infra.feature.qiniu.oss.core.request;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import org.apache.commons.lang3.StringUtils;
import yhao.infra.feature.qiniu.oss.core.BucketInfo;
import yhao.infra.feature.qiniu.oss.core.QiniuBaseRequest;
import yhao.infra.feature.qiniu.oss.core.response.QiniuBaseResponse;

/**
 * 删除空间中的文件
 * @see <a href="https://developer.qiniu.com/kodo/sdk/1239/java#rs-delete">更多明细</a>
 */
public class QiniuDeleteRequest extends QiniuBaseRequest<QiniuBaseResponse> {
    //是否加水印，仅图片有效
    private boolean waterMark;
    //资源路径
    private String url;
    //key值表示资源名，与bucket前缀路径无关，注意，若key不为空，则会使用key而无视url参数
    private String key;


    public QiniuDeleteRequest(boolean waterMark) {
        this.waterMark = waterMark;
    }

    public boolean isWaterMark() {
        return waterMark;
    }

    public String getUrl() {
        return url;
    }

    public String getKey() {
        return key;
    }

    /**
     * key值表示资源名，与bucket前缀路径无关<br/>
     * 注意，若key不为空，则会使用key而无视url参数
     */
    public void setKey(String key) {
        this.key = key;
    }

    /**
     * 优先使用key参数
     */
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    protected QiniuBaseResponse doRequest() {
        BucketInfo bucket = this.isWaterMark()?protectBucket:fileBucket;
        Configuration cfg = new Configuration(bucket.getZone());
        BucketManager bucketManager = new BucketManager(bucket.getAuth(), cfg);
        String key = this.getKey();
        if(StringUtils.isBlank(key)&&StringUtils.isNotBlank(this.getUrl())){
            key = this.getUrl().replace(bucket.getUrl()+"/","");
        }
        if(StringUtils.isBlank(key)){
            throw new RuntimeException("请输入待删除的资源路径");
        }
        try {
            return new QiniuBaseResponse(bucketManager.delete(bucket.getName(), key));
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            throw new RuntimeException(ex.response.toString());
        }
    }
}
